import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {RegisterService} from '../../../services/register.service';
import {Observable, Observer} from 'rxjs';
import {User} from '../../../entity/admin';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  validateForm: FormGroup;

  constructor(private fb: FormBuilder, private registerService: RegisterService) {
  }

  submitForm(): void {
    for (const i of Object.keys(this.validateForm.controls)) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    const user: User = {
      username: this.validateForm.controls.username.value,
      password: this.validateForm.controls.password.value,
      userConfig: {
        username: this.validateForm.controls.username.value,
        nickName: this.validateForm.controls.nickname.value
      }
    };

    this.registerService.registerUser(user).subscribe(response => {
      console.log(response);
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls.password.value) {
      return {confirm: true, error: true};
    }
    return {};
  };

  /** 验证 username 是否可用 */
  userNameAsyncValidator = (control: FormControl) => new Observable((observer: Observer<ValidationErrors | null>) => {
    this.registerService.checkUserName({userName: control.value}).subscribe(response => {
      control.parent.get('nickname').setValue(control.value);
      const {data} = Object.create(response);
      if (data) {
        observer.next(null);
      } else {
        observer.next({error: true, duplicated: true});
      }
    }, error => {
      // you have to return `{error: true}` to mark it as an error event
      observer.next({error: true, duplicated: true});
    }, () => {
      observer.complete();
    });
  });

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required], [this.userNameAsyncValidator]],
      password: [null, [Validators.required]],
      checkPassword: [null, [Validators.required, this.confirmationValidator]],
      email: [null, [Validators.email]],
      nickname: [null],
      phoneNumberPrefix: ['+86'],
      phoneNumber: [null],
      agree: [false]
    });
  }
}
